<template>
    <div class="bg-gray-100 flex-1 p-4">
        <h2 class="text-3xl font-semibold mb-4">用户身份审批</h2>
        <div class="bg-white p-4 rounded-lg shadow-md">
            <var-tabs indicator-color="#006263" active-color="#006263" v-model:active="activeTab">
                <var-tab>
                    <template #default>
                        <var-badge v-if="pendingCount" type="danger" :value="pendingCount" />
                        待审批
                    </template>
                </var-tab>
                <var-tab>已通过</var-tab>
                <var-tab>已驳回</var-tab>
            </var-tabs>
            <div class="max-h-[528px] overflow-y-auto relative">
                <table class="min-w-full mt-4">
                    <thead>
                        <tr>
                            <th v-for="header in headers" :key="header" class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">
                                {{ header }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="listLoading">
                            <td :colspan="headers.length" class="px-6 py-1.4 text-center text-base text-gray-500">
                                <var-loading description="LOADING" color="#006263" />
                            </td>
                        </tr>
                        <tr v-if="listData.length === 0 && !listLoading">
                            <td :colspan="headers.length" class="py-4 text-center text-gray-500">暂无数据</td>
                        </tr>
                        <tr v-for="(record, index) in listData" :key="record.userId" :class="index % 2 ? 'bg-gray-50' : 'bg-white'" class="hover:bg-gray-100 transition-colors">
                            <td class="px-6 py-1 text-center">{{ record.name || '-' }}</td>
                            <td class="px-6 py-1 text-center">{{ record.identity || '-' }}</td>
                            <td class="px-6 py-1 text-center">{{ formatDate(record.createdAt) }}</td>
                            <td class="px-6 py-1 text-center">
                                <var-button color="#006263" text-color="white" @click="openDetail(record)">查看详情</var-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="flex justify-center mt-6">
                <var-pagination v-model="currentPage" v-model:size="pageSize" :total="total" :size-option="[10, 20, 30]" @change="get" style="color: #006263" />
            </div>
        </div>
    </div>
    <var-popup class="p-9 w-[640px] h-[670px] bg-white rounded-lg shadow-lg" v-model:show="showDetail">
        <var-loading description="LOADING" color="#006263" :loading="loading">
            <!--详情界面弹窗-->
            <div class="w-[90%] h-[300px] mx-auto">
                <var-swipe class="w-full h-full" navigation="hover">
                    <var-swipe-item>
                        <img class="w-full h-full object-cover" :src="selectedRecord.imgUrl" />
                    </var-swipe-item>
                </var-swipe>
                <div class="text-lg mt-6">姓名: {{ selectedRecord.name }}</div>
                <div class="text-lg mt-2">身份: {{ selectedRecord.identity }}</div>
                <div class="text-lg mt-2">科室: {{ selectedRecord.departmentName }}</div>
                <div class="text-lg mt-2">申请时间: {{ formatDate(selectedRecord.createdAt) }}</div>
                <div class="text-lg mt-2">备注: {{ selectedRecord.text }}</div>
                <div class="mt-6 flex justify-center">
                    <var-space :size="[10, 30]">
                        <!-- 待审批 -->
                        <var-button v-if="selectedRecord.validFlag === '2'" type="danger" @click="showRejectModal = true">驳回申请</var-button>
                        <var-button v-if="selectedRecord.validFlag === '2'" color="#006263" text-color="white" @click="approveRequest(selectedRecord)">通过审核</var-button>
                        <!-- 已通过 -->
                        <var-button v-if="selectedRecord.validFlag === '1'" type="danger" @click="confirmReject">撤销</var-button>
                        <!-- 已驳回 -->
                        <var-button v-if="selectedRecord.validFlag === '0'" type="danger" @click="confirmReject">撤销驳回</var-button>
                    </var-space>
                </div>
            </div>
        </var-loading>
    </var-popup>
    <var-popup v-model:show="showRejectModal">
        <!--驳回界面弹窗-->
        <var-loading description="LOADING" color="#006263" :loading="loadingDatail">
            <div class="p-9 w-[500px] h-[670px] bg-white rounded-lg shadow-lg">
                <h3 class="text-2xl font-semibold mt-2">常见原因</h3>
                <div v-for="(reason, index) in rejectReasons" :key="index">
                    <var-checkbox v-model="reason.checked" checked-color="#006263">{{ reason.label }}</var-checkbox>
                </div>
                <p class="text-2xl font-semibold mb-2">其他原因</p>
                <var-input variant="outlined" placeholder="请输入驳回原因" focus-color="#006263" textarea v-model="rejectReason" />
                <div class="mt-4 flex justify-center">
                    <var-space :size="[10, 30]">
                        <var-button type="danger" @click="confirmReject">确认驳回</var-button>
                        <var-button @click="showRejectModal = false">取消</var-button>
                    </var-space>
                </div>
            </div>
        </var-loading>
    </var-popup>
</template>

<script>
import dayjs from 'dayjs';

export default {
    name: 'appropvals',
    data() {
        return {
            headers: ['姓名', '身份', '请求时间', '操作'],
            listData: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            pendingCount: 0,
            activeTab: 0,
            loading: false,
            listLoading: false,
            loadingDatail: false,
            showDetail: false,
            showRejectModal: false,
            selectedRecord: null,
            rejectReasons: [
                { label: '科室信息有误', checked: false },
                { label: '身份证号码有误', checked: false },
                { label: '图片信息模糊', checked: false },
                { label: '证件不齐全', checked: false },
                { label: '系统身份与证件不匹配', checked: false }
            ],
            rejectReason: '' // 其他原因
        };
    },
    computed: {},
    watch: {
        activeTab(newVal, oldVal) {
            // 只有在 activeTab 真正变化时才调用 fetchData
            if (newVal !== oldVal) {
                this.currentPage = 1;
                this.fetchData();
            }
        }
    },
    async mounted() {
        await this.fetchData();
    },
    methods: {
        formatDate(date) {
            return dayjs(date).format('YYYY年MM月DD日 HH:mm');
        },
        async fetchData() {
            this.listData = [];
            const typeMap = [2, 1, 0]; // activeTab = 0 -> type = 2; activeTab = 1 -> type = 1; activeTab = 2 -> type = 0
            const type = typeMap[this.activeTab];
            this.listLoading = true;
            const res = await this.$api.user.getUserIdentityImg({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                type: type
            });
            this.listLoading = false;
            if (res.success) {
                this.listData = res.data.list;
                this.total = res.data.total || 0;
                if (type === 2) {
                    this.pendingCount = this.total;
                }
            } else {
                this.$api.notify.error(res.error);
            }
        },
        get(page, pageSize) {
            // 分页跳转
            if (page !== this.currentPage) {
                this.currentPage = page;
                this.fetchData();
            }
            if (this.pageSize !== pageSize) {
                this.pageSize = pageSize;
                this.currentPage = 1; // 切换分页大小时重置到第一页
                this.fetchData();
            }
        },
        openDetail(record) {
            this.selectedRecord = record;
            this.showDetail = true;
        },
        async approveRequest(record) {
            this.loading = true;
            const res = await this.$api.user.approveUserIdentityImg({
                userId: record.userId,
                validFlag: 1
            });
            this.loading = false;
            if (res.success) {
                this.$api.notify.success('通过审核成功');
                await this.fetchData();
                this.showDetail = false;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        async confirmReject() {
            if (this.selectedRecord.validFlag == 1) {
                this.loading = true;
                const res = await this.$api.user.approveUserIdentityImg({
                    userId: this.selectedRecord.userId,
                    validFlag: 2
                });
                this.loading = false;
                if (res.success) {
                    this.$api.notify.success('撤销成功');
                    await this.fetchData();
                    this.showDetail = false;
                    this.showRejectModal = false;
                } else {
                    this.$api.notify.error(res.error);
                }
                return;
            }
            if (this.selectedRecord.validFlag == 0) {
                this.loading = true;
                const res = await this.$api.user.approveUserIdentityImg({
                    userId: this.selectedRecord.userId,
                    validFlag: 2
                });
                this.loading = false;
                if (res.success) {
                    this.$api.notify.success('撤销成功');
                    await this.fetchData();
                    this.showDetail = false;
                    this.showRejectModal = false;
                } else {
                    this.$api.notify.error(res.message);
                }
                return;
            }
            const selectedReasons = this.rejectReasons
                .filter((reason) => reason.checked) // 筛选出选中的原因
                .map((reason) => reason.label); // 提取标签
            if (selectedReasons.length === 0 && !this.rejectReason.trim()) {
                this.$api.notify.error('请选择驳回原因！');
                return;
            }
            if (this.rejectReason.trim()) {
                selectedReasons.push(this.rejectReason.trim()); // 添加其他原因
            }
            const reasonsString = selectedReasons.join('；'); // 拼接成字符串，用分号分隔
            this.loadingDatail = true;
            const res = await this.$api.user.approveUserIdentityImg({
                userId: this.selectedRecord.userId,
                validFlag: 0,
                text: reasonsString
            });
            this.loadingDatail = false;
            if (res.success) {
                this.$api.notify.success('已驳回申请');
                await this.fetchData();
                this.showRejectModal = false;
                this.showDetail = false;
                this.rejectReasons.forEach((reason) => (reason.checked = false));
                this.rejectReason = '';
            } else {
                this.$api.notify.error(error.messaage);
            }
        }
    }
};
</script>
